#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     rest_flask
# @File:        auth.py
# @Author:      Fan GuiChuan
# @Date:        2025/6/26 13:45
# @Version:     Python3.7
# @Description:
import json
import os
from datetime import datetime
from functools import wraps

from flask import request
from app.utils.response import error_response, success_response
from utils.u_crypto import UCrypto
from utils.u_datetime import UDateTime
from utils.u_log import ULog

log_config = json.loads(os.environ['LOG_CONFIG'])
logger = ULog.get_logger('author', log_config)
inner_code = 'dcc_api'
valid_auth_code = [inner_code, 'dcc_wlgf']


def is_valid_date(date_str):
    if not date_str or len(date_str) != 8:
        return False
    new_date_str = f'{date_str[:4]}-{date_str[4:6]}-{date_str[6:]} 00:00:00'
    if not UDateTime.is_valid_datetime_str(new_date_str):
        return False
    diff_day = UDateTime.diff_days(new_date_str, UDateTime.get_cur_time())
    if abs(diff_day) > 1:
        return False
    return True


def is_valid_auth_code(auth_code):
    return auth_code in valid_auth_code


def parse_auth(encrypt_auth):
    if not encrypt_auth:
        logger.error('无鉴权信息请求，拒绝服务！')
        return False, '', ''
    try:
        decrypt_auth = UCrypto.decrypt(encrypt_auth, cipher_encoding='base64')
        if not decrypt_auth or len(decrypt_auth) != 32:
            logger.error(f'鉴权信息不合法：{encrypt_auth}')
            return False, '', ''
        auth_code = decrypt_auth[8:16]
        _date = decrypt_auth[24:]
        logger.debug(f'auth code: {auth_code}, auth date: {_date}')
        return True, auth_code, _date
    except Exception as e:
        logger.exception(str(e))
        return False, '', ''


def gen_token():
    date = datetime.now().strftime('%Y%m%d')
    plaintext = f'qwerasdfdcc_wlgfzxcvasdf{date}'
    encrypted_text = UCrypto.encrypt(plaintext, cipher_encoding='base64')
    return encrypted_text.decode()


def login_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        authorization = request.headers.get('Authorization', None)
        logger.debug(f'鉴权信息：{authorization}')
        parse_res, auth_code, _date = parse_auth(authorization)
        if not parse_res:
            logger.debug(f'鉴权信息解析错误')
            return error_response(f'鉴权信息解析错误')

        if not is_valid_auth_code(auth_code) or not is_valid_date(_date):
            logger.debug(f'鉴权信息授权码或日期不对')
            return error_response(f'鉴权信息授权码或日期不对')

        return func(*args, **kwargs)
    return decorated_view
